package cn.clementine.core.utils;

import cn.clementine.core.entity.Terminal;
import cn.clementine.core.svc.WebShell;
import cn.dev33.satoken.stp.StpUtil;
import com.pty4j.PtyProcess;
import com.pty4j.PtyProcessBuilder;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@Component
public class LocalTerminalHandler extends TextWebSocketHandler {
    @Resource
    WebShell webShell;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        URI uri = session.getUri();
        String id = null;
        String tid = null;
        if (uri != null) {
            id = (String) session.getAttributes().get("clementine-token");
            tid = (String) session.getAttributes().get("tid");
        }
        ;
        if (id != null && tid !=null) {
            if(!webShell.getTerminals().containsKey(tid)){
                CreateNewTerminal(tid,session);
            }{
                Terminal terminal = webShell.getTerminals().get(tid);
                if(terminal.getTerminal_process().isAlive()){

                }
                if(!terminal.isAlive()){
                    terminal.setTerminal_session(session);
                    terminal.start();
                } else if (!terminal.getTerminal_session().equals(session)) {
                    terminal.setTerminal_session(session);
                };
            }

        }else{
            session.close();
        }
    }
    protected void CreateNewTerminal(String tid,WebSocketSession session) throws IOException {
        String[] cmd = {"cmd.exe"};
        PtyProcess process = new PtyProcessBuilder().setCommand(cmd).setInitialColumns(160)
                .setInitialRows(24).start();
        var processOutputStream = process.getOutputStream();
        var processInputStream = process.getInputStream();

        Terminal terminal = new Terminal("终端",processOutputStream,processInputStream,session,process);
        webShell.getTerminals().put(tid,terminal);
        webShell.getTerminals().get(tid).start();
    }
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        MultiValueMap<String, String> parameters = UriComponentsBuilder.fromUri(Objects.requireNonNull(session.getUri())).build().getQueryParams();
        List<String> tid_param = parameters.get("tid");
        String tid = null;
        if(tid_param!=null){
            for(String value: tid_param){
                tid = value;
            }
        }
        String cmd = message.getPayload();
        Terminal terminal = webShell.getTerminals().get(tid);
        terminal.getTerminal_output_stream().write(cmd.getBytes(StandardCharsets.UTF_8));
        terminal.getTerminal_output_stream().flush();
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // if(processOutputStream!=null) processOutputStream.close();
        // process.destroy();
    }
}